package SocketLearn.NetSocketLearn;



import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-06 14:45
 * @description
 * 例题2：客户端发送文件给服务端，服务端接收文件保存在本地
 */
public class TCPTest2 {

    @Test
    public void client(){
        Socket socket=null;
        OutputStream os=null;
        FileInputStream fis=null;
        try {
            String path="C:\\Users\\Lenl\\OneDrive\\图片\\Saved Pictures\\壁纸\\chuyin.jpg";
            socket=new Socket(InetAddress.getByName("127.0.0.1"),9900);
            os=socket.getOutputStream();
            fis=new FileInputStream(new File(path));
            byte[] buffer=new byte[1024];
            int len;
            while((len=fis.read(buffer))!=-1){
                os.write(buffer,0,len);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Test
    public void server() throws IOException{
        String path="D:\\Java Learn\\IOLearnTestFile\\picturetest\\chuyin.jpg";
        ServerSocket ss=new ServerSocket(9900);
        Socket s=ss.accept();
        InputStream is=s.getInputStream();

        FileOutputStream fos=new FileOutputStream(new File(path));
        byte[] buffer=new  byte[1024];
        int len;
        while((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        System.out.println("接收完成！");

        ss.close();;
        s.close();;
        fos.close();
    }
}
